"""
File Name: Pycharm
Description:   base_bot 浏览器做任务
Author: Panwj
Date: 2025/9/6 6:17
"""
import datetime
import json
import random
import time
import uuid
from enum import Enum

from DrissionPage._configs.chromium_options import ChromiumOptions
from DrissionPage._pages.chromium_page import ChromiumPage
from fake_useragent import UserAgent
from loguru import logger


class RegisterBase(object):
    name = '__base_bot__'

    def __init__(self):
        self.home_url = None
        self.is_login = False
        self.is_active = False  # 是否活跃
        self.active_interval = (60, 120)  # 活跃周期
        self.page = None

    def random_ua_list(self):
        ua_list = []
        for i in range(10):
            uas = [UserAgent().getChrome, UserAgent().getFirefox, UserAgent().getEdge, UserAgent().getOpera]
            for ua in uas:
                if ua["type"] == 'desktop' and ua['os'] == 'Windows':
                    ua_list.append(ua['useragent'])
        return list(set(ua_list))

    def get_proxy_v2(self):
        return None

    def load_page(self):
        try:
            co = ChromiumOptions().auto_port(True)
            co.incognito()  # 无痕模式
            # co.headless()  # 无头模式
            # user_data_dir = f"./user_data/{str(uuid.uuid4())}"
            # co.set_argument('--no-sandbox')  # 无沙盒模式
            # co.set_argument('--headless', 'new')
            # co.set_argument('browser_path', '/usr/bin/google-chrome')
            # co.set_user_data_path(user_data_dir)  # 隔离用户数据
            # ========================
            # co.set_argument('--start-maximized')
            # co.set_argument('--window-size', '1500,800')  # 窗口大小会影响列表页获取数据的数量
            # ========================
            co.set_argument('--window-size', '1000,600')
            co.headless = False
            # # 设置 HTTP 代理
            # proxy_dict = get_proxy()
            proxy_dict = self.get_proxy_v2()
            if proxy_dict:
                proxy = f"http://{proxy_dict['ip']}:{proxy_dict['port']}"
                logger.info(f"设置代理: {proxy}")
                co.set_proxy(proxy)
            # co.set_proxy('http://127.0.0.1:7890')
            login_page = ChromiumPage(co)
            # 需要pc端的ua
            # ua_list = self.random_ua_list()
            # if ua_list:
            #     ua = random.choice(ua_list)
            # # 概率较低
            # else:
            ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0"
            print(ua)
            login_page.set.user_agent(ua)
            self.page = login_page
        except Exception as e:
            print(f"创建登录页面失败: {e}")
            return None

    def start_register(self):
        pass

    def save_cookies(self, email_address, email_password, account_password, cookies):
        """
        保存cookie中
        :param email_address:
        :param email_password:
        :param account_password:
        :param cookies:
        :return:
        """
        now_date = datetime.datetime.now()
        file_name = f'{self.name}_{now_date.year}{now_date.month}{now_date.day}.txt'
        with open(file_name, "a", encoding="utf-8") as f:
            f.write(json.dumps({
                'email_address': email_address,
                'email_password': email_password,
                'account_password': account_password,
                'cookies': cookies
            }))
            f.write('\n')
